<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="父级菜单" prop="parent_id">
            <el-tree-select
              v-model="form.parent_id"
              :data="menuTreeOptions"
              :props="treeProps"
              placeholder="请选择父级菜单（不选则为根菜单）"
              clearable
              check-strictly
              :render-after-expand="false"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="菜单名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入菜单名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="路由路径" prop="path">
            <el-input
              v-model="form.path"
              placeholder="请输入路由路径，如：/system/user"
              maxlength="200"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="组件路径" prop="component">
            <el-input
              v-model="form.component"
              placeholder="请输入组件路径，如：system/user/index"
              maxlength="200"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="重定向路径" prop="redirect">
            <el-input
              v-model="form.redirect"
              placeholder="请输入重定向路径（可选）"
              maxlength="200"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="form.sort"
              :min="0"
              :max="9999"
              placeholder="排序值"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="是否隐藏" prop="hidden">
            <el-radio-group v-model="form.hidden">
              <el-radio :label="false">显示</el-radio>
              <el-radio :label="true">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="Meta配置">
        <div class="meta-editor">
          <el-tabs v-model="activeMetaTab" type="card">
            <el-tab-pane label="可视化编辑" name="visual">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="页面标题">
                    <el-input
                      v-model="metaForm.title"
                      placeholder="请输入页面标题"
                      maxlength="50"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="图标">
                    <el-input
                      v-model="metaForm.icon"
                      placeholder="请输入图标名称，如：User"
                      maxlength="50"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="固定标签页">
                    <el-switch v-model="metaForm.affix" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="隐藏面包屑">
                    <el-switch v-model="metaForm.hideBreadcrumb" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>

            <el-tab-pane label="JSON编辑" name="json">
              <el-input
                v-model="form.meta"
                type="textarea"
                :rows="6"
                placeholder="请输入有效的JSON格式Meta配置"
                @blur="validateMetaJson"
              />
              <div v-if="metaJsonError" class="meta-error">
                <el-text type="danger">{{ metaJsonError }}</el-text>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getAllMenus, createMenu, updateMenu, type Menu } from '@/api/menu'
import { MenuMetaHelper } from '@/api/menu'

interface Props {
  visible: boolean
  menuData?: Menu | null
  parentMenu?: Menu | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const activeMetaTab = ref('visual')
const metaJsonError = ref('')
const menuTreeOptions = ref<Menu[]>([])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 对话框标题
const dialogTitle = computed(() => {
  if (props.menuData) {
    return '编辑菜单'
  } else if (props.parentMenu) {
    return `添加子菜单 - ${props.parentMenu.name}`
  } else {
    return '新增菜单'
  }
})

// 是否为编辑模式
const isEdit = computed(() => !!props.menuData)

// 树形选择器属性
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 表单数据
const form = reactive({
  parent_id: undefined as number | undefined,
  name: '',
  path: '',
  component: '',
  redirect: '',
  meta: '',
  sort: 0,
  hidden: false,
  status: 1
})

// Meta表单数据
const metaForm = reactive({
  title: '',
  icon: '',
  affix: false,
  hideBreadcrumb: false
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '菜单名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  path: [
    { max: 200, message: '路径长度不能超过 200 个字符', trigger: 'blur' }
  ],
  component: [
    { max: 200, message: '组件路径长度不能超过 200 个字符', trigger: 'blur' }
  ],
  redirect: [
    { max: 200, message: '重定向路径长度不能超过 200 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '排序值范围为 0-9999', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 监听菜单数据变化
watch(() => props.menuData, (newData) => {
  if (newData) {
    form.parent_id = newData.parent_id
    form.name = newData.name
    form.path = newData.path || ''
    form.component = newData.component || ''
    form.redirect = newData.redirect || ''
    form.meta = newData.meta ? MenuMetaHelper.stringifyMeta(newData.meta) : ''
    form.sort = newData.sort
    form.hidden = newData.hidden
    form.status = newData.status

    // 解析Meta数据到可视化表单
    if (newData.meta) {
      const meta = typeof newData.meta === 'string' ? MenuMetaHelper.parseMeta(newData.meta) : newData.meta
      metaForm.title = meta.title || ''
      metaForm.icon = meta.icon || ''
      metaForm.affix = meta.affix || false
      metaForm.hideBreadcrumb = meta.hideBreadcrumb || false
    }
  } else {
    resetForm()
  }
}, { immediate: true })

// 监听父菜单变化
watch(() => props.parentMenu, (newParent) => {
  if (newParent && !props.menuData) {
    form.parent_id = newParent.id
  }
}, { immediate: true })

// 监听可视化Meta表单变化，同步到JSON
watch(metaForm, () => {
  if (activeMetaTab.value === 'visual') {
    const meta = {
      title: metaForm.title || undefined,
      icon: metaForm.icon || undefined,
      affix: metaForm.affix || undefined,
      hideBreadcrumb: metaForm.hideBreadcrumb || undefined
    }

    // 移除undefined值
    Object.keys(meta).forEach(key => {
      if (meta[key as keyof typeof meta] === undefined) {
        delete meta[key as keyof typeof meta]
      }
    })

    form.meta = Object.keys(meta).length > 0 ? MenuMetaHelper.stringifyMeta(meta) : ''
  }
}, { deep: true })

// 监听JSON Meta变化，同步到可视化表单
watch(() => form.meta, (newMeta) => {
  if (activeMetaTab.value === 'json' && newMeta) {
    try {
      const meta = MenuMetaHelper.parseMeta(newMeta)
      metaForm.title = meta.title || ''
      metaForm.icon = meta.icon || ''
      metaForm.affix = meta.affix || false
      metaForm.hideBreadcrumb = meta.hideBreadcrumb || false
      metaJsonError.value = ''
    } catch (error) {
      // JSON格式错误，不更新可视化表单
    }
  }
})

// 加载菜单选项
async function loadMenuOptions() {
  try {
    const menus = await getAllMenus()
    // 过滤掉当前编辑的菜单及其子菜单，避免循环引用
    if (props.menuData) {
      menuTreeOptions.value = filterMenuOptions(menus, props.menuData.id)
    } else {
      menuTreeOptions.value = menus
    }
  } catch (error) {
    console.error('Failed to load menu options:', error)
  }
}

// 过滤菜单选项，避免循环引用
function filterMenuOptions(menus: Menu[], excludeId: number): Menu[] {
  return menus.filter(menu => {
    if (menu.id === excludeId) {
      return false
    }
    if (menu.children) {
      menu.children = filterMenuOptions(menu.children, excludeId)
    }
    return true
  })
}

// 验证Meta JSON格式
function validateMetaJson() {
  if (!form.meta) {
    metaJsonError.value = ''
    return true
  }

  if (MenuMetaHelper.validateMeta(form.meta)) {
    metaJsonError.value = ''
    return true
  } else {
    metaJsonError.value = 'JSON格式错误，请检查语法'
    return false
  }
}

// 重置表单
function resetForm() {
  form.parent_id = props.parentMenu?.id
  form.name = ''
  form.path = ''
  form.component = ''
  form.redirect = ''
  form.meta = ''
  form.sort = 0
  form.hidden = false
  form.status = 1

  // 重置Meta表单
  metaForm.title = ''
  metaForm.icon = ''
  metaForm.affix = false
  metaForm.hideBreadcrumb = false

  metaJsonError.value = ''
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return

  // 验证Meta JSON格式
  if (!validateMetaJson()) {
    activeMetaTab.value = 'json'
    return
  }

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const submitData = {
          parent_id: form.parent_id || undefined,
          name: form.name,
          path: form.path || undefined,
          component: form.component || undefined,
          redirect: form.redirect || undefined,
          meta: form.meta || undefined,
          sort: form.sort,
          hidden: form.hidden,
          status: form.status
        }

        if (isEdit.value) {
          await updateMenu(props.menuData!.id, submitData)
          ElMessage.success('更新成功')
        } else {
          await createMenu(submitData)
          ElMessage.success('创建成功')
        }

        emit('success')
        handleClose()
      } catch (error) {
        console.error('Submit failed:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 关闭对话框
function handleClose() {
  dialogVisible.value = false
  formRef.value?.resetFields()
  resetForm()
  activeMetaTab.value = 'visual'
}

// 初始化
onMounted(() => {
  loadMenuOptions()
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.meta-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
}

.meta-error {
  margin-top: 8px;
}

:deep(.el-textarea__inner) {
  resize: none;
}

:deep(.el-tabs__content) {
  padding-top: 16px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}
</style>
